package com.example.administrator.printoutindemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.example.administrator.printoutindemo.services.dyjApplication;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.List;


public class LoginGPSActivity extends Activity{

	ProgressDialog progressDiaog;

	private EditText edtUser = null;
	private EditText edtPwd = null;
	private TextView lbl_version = null;
	private Button btnLogin = null;
	private CheckBox login_cb_isRemember = null;
	private Button btnSet = null;

	private UserInfo userInfo = null;

	private String SYSException = "";

	private static final String WEBSERVICE_CONFIG = "webServiceInfo";
	private static final String REMEMBERLOGIN = "rememberLogin";

	private static final int LOGINSUCCESS = 0;
	private static final int USERPASSWORDERRO = 1;
	private static final int NETWORKERROR = 2;
	private static final int SYSERROR = 3;

	private final Handler hanlder = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
				case LOGINSUCCESS:

					String rolesId = ((dyjApplication) getApplication())
							.get_roles_id();
					// 仓管员的rolesId为2,跳转到扫码页面
					if (rolesId.equals("2")) {
						Intent listIntent1 = new Intent();
						listIntent1.setClass(LoginGPSActivity.this,
								ListByQRCodeActivity.class);
						startActivity(listIntent1);
					}
					// 物料员的rolesId为3,跳转到扫码页面
					if (rolesId.equals("3")) {
						Intent listIntent1 = new Intent();
						listIntent1.setClass(LoginGPSActivity.this,
								StoreSubmitProject1Activity.class);
						startActivity(listIntent1);
					}
					// 审核人的rolesId为4,跳转到扫码页面
					if (rolesId.equals("4")) {
						Intent listIntent1 = new Intent();
						listIntent1.setClass(LoginGPSActivity.this,
								StoreOutStorageCheckList1Activity.class);
						startActivity(listIntent1);
					}

					// gps使用人的rolesId为-1,跳转到扫码页面
					if (rolesId.equals("-1")) {
						Intent listIntent1 = new Intent();
						listIntent1.setClass(LoginGPSActivity.this,
								GPSMainActivity.class);
						startActivity(listIntent1);
					}

					progressDiaog.dismiss();
					break;

				case USERPASSWORDERRO:

					Toast.makeText(LoginGPSActivity.this, "用户名密码不正确!",
							Toast.LENGTH_LONG).show();

					progressDiaog.dismiss();
					break;

				case NETWORKERROR:

					Toast.makeText(LoginGPSActivity.this, "网络或系统异常!",
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;
				case SYSERROR:

					Toast.makeText(LoginGPSActivity.this, "系统异常!"+SYSException,
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;

				default:
					progressDiaog.dismiss();
					break;
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loginpage);

		this.setTitle("系统登录");

		edtUser = (EditText) findViewById(R.id.login_edit_account);
		edtPwd = (EditText) findViewById(R.id.login_edit_pwd);
		btnLogin = (Button) findViewById(R.id.login_btn_login);
		btnSet = (Button) findViewById(R.id.login_btn_set);
		login_cb_isRemember = (CheckBox) findViewById(R.id.login_cb_isRemember);
//		lbl_version = (TextView) findViewById(R.id.lbl_version);

		userInfo = new UserInfo();

		SharedPreferences spRemember = getSharedPreferences(REMEMBERLOGIN, 0);

		if (spRemember.getBoolean("ISCHECK", true)) {
			// 设置默认是记录密码状态
			login_cb_isRemember.setChecked(true);
			edtUser.setText(spRemember.getString("name", ""));
			edtPwd.setText(spRemember.getString("pass", ""));

		}

		// 监听是否记住密码
		login_cb_isRemember
				.setOnCheckedChangeListener(new login_cb_isRememberChange());

		btnSet.setOnClickListener(new btnSetClick());
		btnLogin.setOnClickListener(new btnLoignClick());
	}

	private class btnSetClick implements OnClickListener {
		@Override
		public void onClick(View v) {

			Intent intent = new Intent();
			intent.setClass(LoginGPSActivity.this, WebserviceConfigActivity.class);
			startActivity(intent);

		}
	}

	private class btnLoignClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (edtUser.getText().toString().length() == 0) {

				int[] location = new int[2];
				btnLogin.getLocationOnScreen(location);

				Toast toast = Toast.makeText(LoginGPSActivity.this, "请输入用户名!",
						Toast.LENGTH_LONG);

				toast.setGravity(Gravity.LEFT | Gravity.TOP, location[0],
						location[1]);
				toast.show();

				return;

			}

			if (edtPwd.getText().toString().length() == 0) {

				int[] location = new int[2];
				btnLogin.getLocationOnScreen(location);

				Toast toast = Toast.makeText(LoginGPSActivity.this, "请输入密码!",
						Toast.LENGTH_LONG);

				toast.setGravity(Gravity.LEFT | Gravity.TOP, location[0],
						location[1]);
				toast.show();

				return;
			}

			// 判断是否记住密码
			if (login_cb_isRemember.isChecked()) {
				saveData();
			}

			SharedPreferences sPreferencces = getSharedPreferences(
					WEBSERVICE_CONFIG, 0);

			if (sPreferencces.getString("ip", "") == "") {

				int[] location = new int[2];
				btnLogin.getLocationOnScreen(location);

				Toast toast = Toast.makeText(LoginGPSActivity.this,
						"请配置网络ip地址与端口号!", Toast.LENGTH_LONG);

				toast.setGravity(Gravity.LEFT | Gravity.TOP, location[0],
						location[1]);
				toast.show();

				return;
			}

			progressDiaog = new ProgressDialog(LoginGPSActivity.this);
			progressDiaog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置为圆形进度条
			progressDiaog.setTitle("提示");
			// progressDiaog.setIcon(R.drawable.ic_launcher);//设置进度条的图标
			progressDiaog.setMessage("系统正在努力与服务器联系，请稍后......");
			progressDiaog.setIndeterminate(false);// 设置进度条不明确
			progressDiaog.setCancelable(true);

			progressDiaog.show();

			new Thread(new Runnable() {
				public void run() {

					try {

						int result = callWebService();

						if (result > 0) {// 登录成功
							Message m = new Message();
							m.what = LoginGPSActivity.LOGINSUCCESS;
							hanlder.sendMessage(m);
						} else if (result == 0) {// 用户名密码错误
							Message m = new Message();
							m.what = LoginGPSActivity.USERPASSWORDERRO;
							hanlder.sendMessage(m);
						} else {// 网络系统错误
							Message m = new Message();
							m.what = LoginGPSActivity.NETWORKERROR;
							hanlder.sendMessage(m);
						}

					} catch (Exception e) {
//						SYSException = e.toString();
						Message m = new Message();
						m.what = LoginGPSActivity.SYSERROR;
						hanlder.sendMessage(m);
					}
				}
			}).start();

		}
	}

	private int callWebService() {

		int result = 0;

		try {

			/****************** 调用webService ***********************/
			// 调用.net 的WebService.
			String nameSpace = "http://dyjapp.org/";
			String methodName = "GetGpsUserInfo";
			SharedPreferences sPreferencces = getSharedPreferences(
					WEBSERVICE_CONFIG, 0);

			String url = "http://" + sPreferencces.getString("ip", "") + ":"
					+ sPreferencces.getString("Port", "")
					+ "/StoreService.asmx";

			String soapAction = nameSpace + methodName;

			// 设置连接参数
			SoapObject request = new SoapObject(nameSpace, methodName);

			// 增加属性参数。 将相关的函数参数放入到过程中。
			request.addProperty("user_login", edtUser.getText().toString());
			request.addProperty("user_pass", edtPwd.getText().toString());

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
			// V1.1）;

			// 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
			// 不指定rpc方式则用true否则要用false
			envelope.dotNet = true;

			// envelope.setOutputSoapObject(request);//设置请求参数
			envelope.bodyOut = request; // enveloper.bodyOut=request 与
			// envelope.setOutputSoapObject(request)
			// 效果相同。
			// step4 创建HttpTransportSE对象
			HttpTransportSE ht = new HttpTransportSE(url);
			// step5 调用WebService
			ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
			if (envelope.getResponse() != null) {
				SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
				// if ("1".equals(response.toString())) {
				String t = response.toString();

				if (!t.equals("") && !t.equals("[]")) {

					List<UserInfo> li = userInfo.getListFromJSON(t);

					if (li.size() > 0) {
						UserInfo m = li.get(0);

						((dyjApplication) getApplication()).set_roles_id(m
								.get_roles_id());//
						((dyjApplication) getApplication()).set_user_login(m
								.get_user_login());
						((dyjApplication) getApplication()).set_user_name(m
								.get_user_name());
						((dyjApplication) getApplication()).set_user_id(m
								.get_user_id());
					}

					result = 1;
				}

			} else {

				result = -1;
			}
			/****************** 调用webService结束 ***********************/

		} catch (Exception e) {
			// TODO: handle exception
			progressDiaog.dismiss();
			// hintInfo.setText("异常了，原因:" + e.getMessage());

//			int[] location = new int[2];
//			btnLogin.getLocationOnScreen(location);
//
//			Toast toast = Toast.makeText(LoginGPSActivity.this,
//					"请正确设置IP地址" + e.getMessage(), Toast.LENGTH_LONG);
//
//			toast.setGravity(Gravity.LEFT | Gravity.TOP, location[0],
//					location[1]);
//			toast.show();

			SYSException = e.toString();
			result = -1;
		}

		return result;
	}

	private void saveData() {

		SharedPreferences sPreferencces = getSharedPreferences(REMEMBERLOGIN, 0);

		Editor editor = sPreferencces.edit();
		editor.putString("name", edtUser.getText().toString());
		editor.putString("pass", edtPwd.getText().toString());
		editor.commit();

	}

	private class login_cb_isRememberChange implements OnCheckedChangeListener {
		@Override
		public void onCheckedChanged(CompoundButton buttonView,
									 boolean isChecked) {
			// TODO Auto-generated method stub
			SharedPreferences sp = getSharedPreferences(REMEMBERLOGIN, 0);

			if (login_cb_isRemember.isChecked()) {

				// System.out.println("记住密码已选中");
				sp.edit().putBoolean("ISCHECK", true).commit();

			} else {

				// System.out.println("记住密码没有选中");
				sp.edit().putBoolean("ISCHECK", false).commit();

			}

		}
	}

}